package servlet;

import bean.Role;
import bean.Users;
import service.RoleService;
import service.UsersService;
import service.impl.RoleServiceImpl;
import service.impl.UsersServiceImpl;
import util.PageUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;


@WebServlet(urlPatterns = "/power/user/users")
public class UsersServlet extends HttpServlet {


    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String method = req.getParameter("method");

        if ("insert".equals(method)) {
            insert(req, resp);
        }else if ("findbyid".equals(method)){
            findById(req,resp);
        } else if ("update".equals(method)) {
            update(req, resp);
        }else if ("delete".equals(method)){
            delete(req, resp);
        } else {
            select(req, resp);
        }


    }



    //查询数据
    protected void select(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //接收参数（分页参数+模糊查询参数）
        String index = req.getParameter("index");

        int pageIndex = (index == null || index.length() == 0) ? 1 : Integer.parseInt(index);

        //调取service方法（1.查询数据列表方法 2.查询总条数的方法）

        PageUtil pageUtil = new PageUtil();

        //调取service方法
        UsersService service = new UsersServiceImpl();
        List<Users> usersList = service.getUsersList(pageIndex, pageUtil.getPageSize());
        int total = service.total();

        //工具类存储对象数据
        pageUtil.setTotal(total);
        pageUtil.setPageIndex(pageIndex);
        pageUtil.setDataList(usersList);


        //页面存值，并跳转
        req.setAttribute("page", pageUtil);
        req.getRequestDispatcher("list.jsp").forward(req, resp);


    }




    protected void insert(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //获取页面数据

        String loginName = req.getParameter("loginName");
        String passWord = req.getParameter("passWord");
        String realName = req.getParameter("realName");
        String sex = req.getParameter("sex");
        String email = req.getParameter("email");
        String address = req.getParameter("address");
        String phone = req.getParameter("phone");
        String cardId = req.getParameter("cardId");
        String desc = req.getParameter("desc");
        String roleId = req.getParameter("roleId");


        //将参数封装到用户对象中
        Users users = new Users();
        users.setLoginName(loginName);
        users.setPassWord(passWord);
        users.setRealName(realName);
        users.setSex(Integer.parseInt(sex));
        users.setEmail(email);
        users.setAddress(address);
        users.setPhone(phone);
        users.setCardId(cardId);
        users.setDesc(desc);
        users.setRoleId(Integer.parseInt(roleId));

        //调取service方法，获取数据入库时的影响行数
        UsersService service = new UsersServiceImpl();
        int i = service.insert(users);


        resp.setContentType("text/html;charset=utf-8");
        PrintWriter writer = resp.getWriter();


        if (i > 0) {
            writer.println("<script>alert('新增成功~');location.href='/power/user/users'</script>");

        } else {
            writer.println("<script>alert('新增失败!');location.href='/power/user/getRoleList'</script>");
        }
    }


    protected void findById(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String userId = req.getParameter("userId");
        
        //根据用户主键查询用户信息
        UsersService service = new UsersServiceImpl();
        Users user = service.findById(Integer.parseInt(userId));

        //查询角色列表
        RoleService roleService = new RoleServiceImpl();
        List<Role> roleList = roleService.getList();

        //存值
        req.setAttribute("user",user);
        req.setAttribute("rlist",roleList);

        //转发跳转页面
        req.getRequestDispatcher("edit.jsp").forward(req,resp);


    }

    protected void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //获取页面参数数据
        String userId = req.getParameter("userId");
        String loginName = req.getParameter("loginName");
        String passWord = req.getParameter("passWord");
        String realName = req.getParameter("realName");
        String sex = req.getParameter("sex");
        String email = req.getParameter("email");
        String address = req.getParameter("address");
        String phone = req.getParameter("phone");
        String cardId = req.getParameter("cardId");
        String desc = req.getParameter("desc");
        String roleId = req.getParameter("roleId");

        //存数据对象
        Users user = new Users();

        user.setUserId(Integer.parseInt(userId));
        user.setLoginName(loginName);
        user.setPassWord(passWord);
        user.setRealName(realName);
        user.setSex(Integer.parseInt(sex));
        user.setEmail(email);
        user.setAddress(address);
        user.setPhone(phone);
        user.setCardId(cardId);
        user.setDesc(desc);
        user.setRoleId(Integer.parseInt(roleId));

        //调取service方法
        UsersService service = new UsersServiceImpl();

        int i = service.update(user);

        resp.setContentType("text/html;charset=utf-8");

        PrintWriter writer = resp.getWriter();

        //页面数据更新
        if(i>0){
            writer.println("<script>alert('更新成功');location.href='/power/user/users'</script>");
        }else{
            writer.println("<script>alert('更新失败');location.href='/power/user/users?method=findbyid?userId="+userId+"'</script>");
        }

    }


    /**
     * 删除用户信息
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //获取页面参数数据
        String userId = req.getParameter("userId");

        //调取service方法，通过userId删除用户信息
        UsersService service = new UsersServiceImpl();
        int i = service.delete(Integer.parseInt(userId));

        resp.setContentType("text/html;charset=utf-8");

        PrintWriter writer = resp.getWriter();

        if(i>0){
            writer.println("<script>alert('删除成功');location.href='/power/user/users'</script>");
        }else{
            writer.println("<script>alert('删除失败');location.href='/power/user/users'</script>");
        }


    }


}

